/*
 * Copyright (C) 2010 Google Inc.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.apps.tvremote;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.google.android.apps.tvremote.protocol.ICommandSender;
import com.google.anymote.Key;

/**
 * Main screen of the remote controller activity.
 */
public class LauncherShortcutActivity extends BaseActivity
{
    private static final String LOG_TAG = "LauncherShortcutActivity";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //moveTaskToBack(true);

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        //getConnectionManager().connect(this);
    }

    @Override
    protected void onPause()
    {
        //getConnectionManager().disconnect(this);
        super.onPause();
    }

    public static int getShorcutKeyCode(Activity activity)
    {
        final Intent intent = activity.getIntent();
        if (intent != null)
        {
            return intent.getIntExtra(Intent.EXTRA_KEY_EVENT, -1);
        }
        return -1;
    }

    @Override
    protected void onServiceAvailable(CoreService coreService)
    {
        Log.d(LOG_TAG, "onServiceAvailable");
        super.onServiceAvailable(coreService);

        coreService.connect(this);
    }

    @Override
    public void onConnectionSuccessful(ICommandSender sender)
    {
        Log.d(LOG_TAG, "onConnectionSuccessful");

        super.onConnectionSuccessful(sender);

        int keyCode = getShorcutKeyCode(this);
        if (keyCode >= 0)
        {
            Key.Code code = Key.Code.values()[keyCode];
            getCommands().key(code, Key.Action.DOWN);
            getCommands().key(code, Key.Action.UP);
        }

        this.moveTaskToBack(true);
        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                LauncherShortcutActivity.this.finish();
            }
        }, 250);
    }

    @Override
    public void onDisconnected()
    {
        Log.d(LOG_TAG, "onDisconnected");

        super.onDisconnected();
        this.finish();
    }
}
